import { RedisModule as NestRedisModule, RedisService } from '@liaoliaots/nestjs-redis';
import { Global, Module, Provider } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

import { REDIS_CLIENT } from '~/common/decorators/inject-redis.decorator';

import { ConfigKeyPaths } from '~/config';
import { IRedisConfig } from '~/config/redis.config';
const providers: Provider[] = [
  {
    provide: REDIS_CLIENT,
    useFactory: (redisService: RedisService) => {
      return redisService.getOrThrow();
    },
    inject: [RedisService] // 注入 RedisService
  }
];

@Global()
@Module({
  imports: [
    // redis
    NestRedisModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService<ConfigKeyPaths>) => ({
        readyLog: true,
        config: configService.get<IRedisConfig>('redis')
      }),
      inject: [ConfigService]
    })
  ],
  providers,
  exports: [...providers]
})
export class RedisModule {}
